import HeaderComponent from "@/components/HeaderComponent/HeaderComponent";

import { Input, Toast, Picker } from "antd-mobile";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";

import { upgrade, upgradeEnum, getGoodsList } from "@/api/module/user";
import { getApiToken } from "@/api/module/U2U";
import { CenterPopupComponent } from "@/components/CenterPopupComponent/CenterPopupComponent";

const Step2Component = () => {
  const { t } = useTranslation();

  const [password, setPassword] = useState("");
  const [googleCode, setGoogleCode] = useState("");
  const [upgradeInfo, setUpgradeInfo] = useState<
    Awaited<ReturnType<typeof upgrade>>["data"]
  >({
    get_coin: 0,
    next_level: "",
    price: 0,
    price_jhb: 0,
    price_zcb: 0,
  });

  useEffect(() => {
    requpgrade(upgradeEnum.check);
    goodsList();
  }, []);
  // 获取升级商品
  const [nextLevel, setNextLevel] = useState([]);
  const [visible1, setVisible1] = useState(false);
  const [pickerValue, setPickerValue] = useState<(string | null)[]>();
  const [selectedId, setSelectedId] = useState<number>();
  // 打开弹框的函数
  const handleOpenModal = () => {
    setVisible1(true);
  };
  const goodsList = async () => {
    const res = await getGoodsList();
    if (res.code === 0) {
      setNextLevel(res.data.list_data);
    }
  };
  // 构造Picker的columns，假设nextLevel每个元素都有`name`字段
  const typeColumns = [
    nextLevel.map((item) => ({
      label: item.title, // 显示名称，假设字段是 `name`
      value: item.goods_id, // 使用id作为值
      price: item.price,
      price_zcb: item.price_currency_one,
      price_jhb: item.price_currency_two,
      get_coin: item.get_coin,
    })),
  ];
  // 处理Picker确认后的选中值
  const handlePickerConfirm = (v, extend) => {
    setPickerValue(v); // 更新Picker选中的值

    // 假设你需要将选中的商品id设置到 upgradeInfo 的 next_level
    const selectedId = v[0]; // 选中的商品id
    const selectedLevel = extend.items[0].label; //选中的商品等级
    const get_coin = extend.items[0].get_coin;
    const price = extend.items[0].price;
    const price_jhb = extend.items[0].price_jhb;
    const price_zcb = extend.items[0].price_zcb;
    setSelectedId(selectedId);
    // 更新 upgradeInfo 中的 next_level
    setUpgradeInfo((prevState) => ({
      ...prevState,
      get_coin: get_coin,
      next_level: selectedLevel,
      price: price,
      price_jhb: price_jhb,
      price_zcb: price_zcb,
    }));

    console.log("选中的商品ID:", selectedId);
  };
  const requpgrade = async (type: upgradeEnum) => {
    if (visible) setVisible(false);
    const res = await upgrade({
      action: type,
      node_user_id: "",
      password: password,
      google_code: googleCode,
      APITOKEN: APIToken,
    });
    if (type == upgradeEnum.check && res.code === 0) {
      setUpgradeInfo(res.data);
      return;
    }
    APIToken && setAPIToken("");
    Toast.show({
      content: res.msg,
    });
    if (res.code === 0) {
      setGoogleCode("");
      setPassword("");
    }
  };
  const [visible, setVisible] = useState(false);
  const [APIToken, setAPIToken] = useState("");
  const reqApiToken = async () => {
    try {
      // || !googleCode
      if (!password) {
        Toast.show({
          content: "请输入完整信息",
        });
        return;
      }
      if (!APIToken) {
        const res = await getApiToken();
        setAPIToken(res.data.api_token);
      }
      setVisible(true);
    } catch (error) {
      console.log(error);
    }
  };
  return (
    <div
      className="mt-4 pb-8"
      style={{
        fontSize: "95%",
      }}
    >
      <div
        className="tips text-font-2 text-center mb-8
      "
      >
        {t("pleaseEnter")}
      </div>
      {Object.keys(upgradeInfo).length > 0 &&
        Object.keys(upgradeInfo).map((key) => {
          return (
            <div
              key={key}
              className="flex justify-between items-center mt-4 bg-bg-1 py-4 px-3 rounded-lg"
            >
              {/* <div>{t(key)}</div> */}
              {key != "next_level" && <div>{t(key)}</div>}
              {key == "next_level" && (
                <div>
                  {t(key)}
                  <span style={{ "font-size": "10px" }}>
                    （{t("optional")}）
                  </span>
                </div>
              )}
              <div>
                {key != "next_level" &&
                  upgradeInfo[key as keyof typeof upgradeInfo]}
                {key == "price" ? "USDT" : ""}
                {key == "next_level" && (
                  <div onClick={handleOpenModal}>
                    {upgradeInfo[key as keyof typeof upgradeInfo]}
                  </div>
                )}
              </div>
            </div>
          );
        })}
      <Picker
        cancelText={t("cancel")}
        confirmText={t("confirm")}
        style={{
          // @ts-ignore
          "--adm-color-background": "#242424",
        }}
        className="text-white-1 bg-bg-1"
        columns={typeColumns}
        visible={visible1}
        onClose={() => {
          setVisible1(false);
        }}
        value={pickerValue}
        onConfirm={handlePickerConfirm}
      />
      <div className="receivable mt-4">
        <div>{t("confirmPassword")}</div>
        <Input
          style={{
            "--font-size": "14px",
            "--color": "#fff",
          }}
          className="bg-bg-1 py-4 mt-3 px-3 rounded-lg "
          placeholder={`${t("enter")}`}
          value={password}
          onChange={(val) => {
            setPassword(val);
          }}
        />
      </div>
      {/* <div className="password mt-4">
        <div>{t("googleCode")}</div>
        <Input
          style={{
            "--font-size": "14px",
            "--color": "#fff",
          }}
          type="password"
          className="bg-bg-1 py-4 mt-3 px-3 rounded-lg "
          placeholder={`${t("enter")}`}
          value={googleCode}
          onChange={(val) => {
            setGoogleCode(val);
          }}
        />
      </div> */}
      <div
        onClick={reqApiToken}
        className="mt-6 bg-bg-16 py-4 rounded-md text-center text-base"
      >
        {t("confirm")}
      </div>

      <CenterPopupComponent
        visible={visible}
        setVisible={setVisible}
        title="upgrade"
        content={
          t("UpgradeTo") +
          t(`${typeof upgradeInfo != "string" ? upgradeInfo.next_level : ""}}`)
        }
        onClick={() => requpgrade(upgradeEnum.buy)}
      />
    </div>
  );
};

export default function Upgrade() {
  return (
    <div className="text-white-1 px-4">
      <HeaderComponent title="upgrade" />
      <Step2Component />
    </div>
  );
}
